package com.ragdollcat.thirdaicodegenerate.core.saver;

import cn.hutool.core.io.FileUtil;
import com.ragdollcat.thirdaicodegenerate.ai.model.MultiFileCodeResult;
import com.ragdollcat.thirdaicodegenerate.enums.CodeGenTypeEnum;
import com.ragdollcat.thirdaicodegenerate.model.entity.App;
import com.ragdollcat.thirdaicodegenerate.model.entity.ProjectVersionCtl;
import com.ragdollcat.thirdaicodegenerate.service.AppService;
import com.ragdollcat.thirdaicodegenerate.service.ProjectVersionCtlService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * 多文件保存
 */
@Slf4j
@Component
public class MutliFileSaverTemplate extends CodeFileSaverTemplate<MultiFileCodeResult> {

    @Resource
    private ProjectVersionCtlService projectVersionCtlService;

    @Resource
    private AppService appService;

    @Override
    public String makeUniqueContents(Long appId) {
        return CodeGenTypeEnum.MULTI_FILE.getValue() + "_" + appId;
    }

    @Override
    public void save(String path, MultiFileCodeResult codeParseResult, int version, Long appId,String description) {
        if (codeParseResult.getHtmlCode() != null) {
            doSave(path + File.separator + "index.html", codeParseResult.getHtmlCode(),version,appId, description);
        }
        if (codeParseResult.getCssCode() != null) {
            doSave(path + File.separator + "style.css", codeParseResult.getCssCode(),version,appId, description);
        }
        if (codeParseResult.getJsCode() != null) {
            doSave(path + File.separator + "script.js", codeParseResult.getJsCode(),version,appId, description);
        }
    }

    /**
     * 进行保存
     *
     * @param path        保存的路径
     * @param content     文件内容
     * @param appId
     * @param description
     */
    public void doSave(String path, String content, int version, Long appId, String description) {
        //写文件到项目路径
        FileUtil.writeUtf8String(content, path);

        try {
            App app = appService.getById(appId);
            //保存到版本控制表
            ProjectVersionCtl projectVersionCtl = ProjectVersionCtl.builder().
                    content(content).
                    appId(appId).
                    version(version).
                    fileName(FileUtil.getName(new File(path))).
                    userId(app.getUserId())
                    .message(description)
                    .build();
            projectVersionCtlService.save(projectVersionCtl);
        } catch (Exception e) {
            log.error("保存文件到版本记录表错误，原因：", e);
        }
    }
}
